import express from 'express';
import { client } from './scheme.js';

const noteRoute = express.Router();

noteRoute.post('/getnote', async (req, res) => {
  const {param: {noteID}} = req.body;
  const queryNote = await client.note.findFirstOrThrow({
    where: {noteID: noteID}
  });
  return res.json({
    timestamp: new Date().getTime(),
    api: {version: 'v1.0', status: 200},
    result: {
      description: '查询完成',
      note: {
        noteID: queryNote.noteID,
        title: queryNote.title,
        rawContent: queryNote.content
      }
    }
  });
});

noteRoute.post('/addNote', async (req, res) => {
  const {param: {user: {email}, note}} = req.body;
  const {title, rawContent} = note;
  const userProfile = await client.user.findFirstOrThrow({
    where: {email: email}
  });
  const newNote = await client.note.create({
    data: {
      ownerID: userProfile.userID,
      content: rawContent,
      title: title,
      date: new Date()
    }
  });
  const noteDate = newNote.date;
  return res.json({
    timestamp: new Date().getTime(),
    api: {version: 'v1.0', status: 200},
    result: {
      description: '添加成功',
      noteID: newNote.noteID,
      noteTitle: newNote.title,
      noteDate: `${noteDate.getFullYear()}-${noteDate.getMonth() + 1}-${noteDate.getDate()}`
    }
  });
});

noteRoute.post('/editNote', async (req, res) => {
  const {param: {target}} = req.body;
  const {noteID, isDelete, newNoteConfig} = target;
  if(isDelete) {
    const operateResult = await client.note.delete({
      where: {noteID: noteID}
    });
    if(operateResult){
      return res.json({
        timestamp: new Date().getTime(),
        api: {version: 'v1.0', status: 200},
        result: {
          description: '删除完成'
        }
      });
    }
  } else {
    const {title, content, date} = newNoteConfig;
    const operateResult = await client.note.update({
      where: {noteID: noteID},
      data: {title, content, date: new Date(date)}
    });
    if(operateResult) {
      if(operateResult){
        return res.json({
          timestamp: new Date().getTime(),
          api: {version: 'v1.0', status: 200},
          result: {
            description: '更新成功'
          }
        });
      }
    }
  }
});

noteRoute.post('/getNotes', async (req, res) => {
  const {param: {user: {email}}} = req.body;
  const userWithNotes = await client.user.findUniqueOrThrow({
    where: {email: email},
    include: {note: true}
  });
  const noteList = Array<{
    noteID: string, date: number, title: string
  }>();
  userWithNotes.note.map((elem) => {
    noteList.push({
      noteID: elem.noteID,
      date: elem.date.getTime(),
      title: elem.title ? elem.title : elem.noteID
    });
  });
  return res.json({
    timestamp: new Date().getTime(),
    api: {version: 'v1.0', status: 200},
    result: {
      description: '查询完成',
      queryData: noteList
    }
  });
});

export default noteRoute;